//
//  NoticeListVCViewController.m
//  dyseller
//
//  Created by 红喇叭 on 2017/8/16.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "NoticeListVCViewController.h"
#import "NoticeListCell.h"
#import "CommentsNoticeVC.h"
#import "OrderNoticeVC.h"
#import "AnnounCementVC.h"
#import "HLBTabBarVC.h"
#import "NocticeSetViewController.h"
#import "UITabBarItem+PPBadgeView.h"

@interface NoticeListVCViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSArray *dic;
}

@property(nonatomic,strong)UITableView *tableView;

@end

@implementation NoticeListVCViewController

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self setNavTitle:@"通知" titleColor:[UIColor blackColor] font:font17];
    self.navigationItem.leftBarButtonItem = nil;
   
    if([userDefaults objectForKey:@"NocationList"]){
        dic = [userDefaults objectForKey:@"NocationList"];
    }else{
        dic = @[@{@"type":@"评论",@"content":@"您有新的评论",@"newItem":@"0"},
                @{@"type":@"订单",@"content":@"您有新的订单",@"newItem":@"0"},
                @{@"type":@"公告",@"content":@"您有新的公告",@"newItem":@"0"}];
    }
    
    [self.navigationController.tabBarItem pp_hiddenBadge];
    for (NSDictionary *newdic in dic) {
        if([newdic[@"newItem"] isEqualToString:@"1"]){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                  [self.navigationController.tabBarItem pp_addDotWithColor:[UIColor redColor]];
            });
            break;
        }
    }

    self.tableView.backgroundColor = self.view.backgroundColor;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newComment) name:@"news_Comment" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newOrder) name:@"news_order" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newAdmin) name:@"news_Admins" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadNoction) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if([userDefaults objectForKey:@"NocationList"]){
        dic = [userDefaults objectForKey:@"NocationList"];
    }else{
        dic = @[@{@"type":@"评论",@"content":@"您有新的评论",@"newItem":@"0"},
                @{@"type":@"订单",@"content":@"您有新的订单",@"newItem":@"0"},
                @{@"type":@"公告",@"content":@"您有新的公告",@"newItem":@"0"}];
        [userDefaults setObject:dic forKey:@"NocationList"];
    }
    
    [self hidePage];
    [self.tableView reloadData];
    
    if([userDefaults objectForKey:@"deviceToken"]){
        [self initHeaderView];
    }else{
        self.tableView.tableHeaderView = [UIView new];
        
    }

}

- (void)hidePage{
    [self.navigationController.tabBarItem pp_hiddenBadge];
    for (NSDictionary *newdic in dic) {
        if([newdic[@"newItem"] intValue]>0){
            [self.navigationController.tabBarItem pp_addDotWithColor:[UIColor redColor]];
            break;
        }
    }

}

//请求新的评论的列表
- (void)loadNoction{
    __weak typeof(self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Notice/getUnread" isactive:YES parameter:@{} successBlock:^(PPHttpRequest *request, id responseObj) {
        NSMutableArray *arr = dic.mutableCopy;
        for(int i=0;i<3;i++){
            NSMutableDictionary *newdic = ((NSDictionary *)dic[i]).mutableCopy;
            if(i == 0){
                newdic[@"newItem"] = [NSString stringWithFormat:@"%d",[responseObj[@"comment"] intValue]];
            }else if (i==1){
               newdic[@"newItem"] = [NSString stringWithFormat:@"%d",[responseObj[@"order"] intValue]];
            }else{
               newdic[@"newItem"] = [NSString stringWithFormat:@"%d",[responseObj[@"notice"] intValue]];
            }
            arr[i] = newdic;
        }
        dic = arr;
        [userDefaults setObject:dic forKey:@"NocationList"];
        [weakself.tableView reloadData];
        [weakself hidePage];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}

//收到新评论的推送的处理
- (void)newComment{
    NSMutableArray *arr = dic.mutableCopy;
     NSMutableDictionary *newdic = ((NSDictionary *)dic[0]).mutableCopy;
    newdic[@"newItem"] = [NSString stringWithFormat:@"%d",[newdic[@"newItem"] intValue]+1];
    arr[0] = newdic;
    dic = arr;
    [userDefaults setObject:dic forKey:@"NocationList"];
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
     [self.navigationController.tabBarItem pp_addDotWithColor:[UIColor redColor]];
}

//收到新订单推送的处理
- (void)newOrder{
    NSMutableArray *arr = dic.mutableCopy;
    NSMutableDictionary *newdic = ((NSDictionary *)dic[1]).mutableCopy;
    newdic[@"newItem"] = [NSString stringWithFormat:@"%d",[newdic[@"newItem"] intValue]+1];
    arr[1] = newdic;
    dic = arr;
    [userDefaults setObject:dic forKey:@"NocationList"];
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    
     [self.navigationController.tabBarItem pp_addDotWithColor:[UIColor redColor]];
    
}

//收到新的公告的处理
- (void)newAdmin{
 
    NSMutableArray *arr = dic.mutableCopy;
     NSMutableDictionary *newdic = ((NSDictionary *)dic[2]).mutableCopy;
    newdic[@"newItem"] = [NSString stringWithFormat:@"%d",[newdic[@"newItem"] intValue]+1];
    arr[2] = newdic;
    dic = arr;
    [userDefaults setObject:dic forKey:@"NocationList"];
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    
     [self.navigationController.tabBarItem pp_addDotWithColor:[UIColor redColor]];
}

- (void)initHeaderView{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 30)];
    headView.backgroundColor = UIColorFromRGB(0xfa6381);
    UILabel *tsLab = [[UILabel alloc] init];
    tsLab.textColor  = kWhiteColor;
    tsLab.text = @"推送开启失败，请点击此处重新开启";
    tsLab.font = font15;
    tsLab.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:tsLab];
    tsLab.sd_layout.centerYEqualToView(headView).leftSpaceToView(headView, 0).rightSpaceToView(headView, 0).heightIs(20);
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setNoticeAction)];
    [headView addGestureRecognizer:tap];
    self.tableView.tableHeaderView = headView;
}

- (void)setNoticeAction{
    NocticeSetViewController *vc = [NocticeSetViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableView *)tableView{
    if(_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-TabBarItemHeight-NavigationHeight+49) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"NoticeListCell" bundle:nil] forCellReuseIdentifier:@"NoticeListCell"];
        _tableView.scrollEnabled = NO;

        //UITableView去掉自带系统的分割线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark --UITableViewDelegate UITableDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NoticeListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoticeListCell" forIndexPath:indexPath];
    [cell setCellData:dic[indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(indexPath.row == 0){
        cell.NocticeImg.image = [UIImage imageNamed:@"note_icon3_default_nor.png"];
    }else if (indexPath.row == 1){
        cell.NocticeImg.image = [UIImage imageNamed:@"note_icon2_default_nor.png"];
    }else{
        cell.NocticeImg.image = [UIImage imageNamed:@"note_icon1_default_nor.png"];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 75;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //点击评论列表
    if(indexPath.row == 0 ){
        CommentsNoticeVC *vc = [[CommentsNoticeVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.row == 1){
        
        OrderNoticeVC *vc = [[OrderNoticeVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        AnnounCementVC *vc = [[AnnounCementVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

@end
